<?php

require_once 'Pipes/Decorator.php';
require_once 'Pipes/Xml/Element.php';
require_once 'Pipes/Xml/Attr.php';

class Pipes_Xml_Document
    extends Pipes_Decorator
{
    public function __construct()
    {
        $this->_decorated = new DOMDocument();
        $this->formatOutput = true;
    }
    
    public function __get($key)
    {
        switch ($key) {
            case 'documentElement' :
                $returnObject = 'Pipes_Xml_Element';
                break;
            
            default:
                return parent::__get($key);
                break;
        }
        
        return new $returnObject($this->_decorated->$key);
    }
    
    public function createElement($name)
    {
        return new Pipes_Xml_Element($this->_decorated->createElement($name));
    }
    
    public function createAttribute($name)
    {
        return new Pipes_Xml_Attr($this->_decorated->createAttribute($name));
    }
    
    public function appendChild($element)
    {
        $this->_decorated->appendChild($element->domNode());
    }
    
    public function getElementsByTagName($tagName)
    {
        return new Pipes_Xml_NodeList(
            $this->_decorated->getElementsByTagName($tagName)
        );
    }
    
    public function importNode(Pipes_Xml_Node $node, $deep = false)
    {
        return new Pipes_Xml_Element($this->_decorated->importNode($node->domNode(), $deep));
    }
    
    public function domDocument()
    {
        return $this->_decorated;
    }
    
    public function render()
    {
        return preg_replace(
            array(
                '/\s?xmlns:pipes="[^"]+"\s?/',
                "/<\?xml version=\"[0-9]+\.[0-9]+\"\?>\n?/"
            ),
            '',
            $this->domDocument()->saveXML()
        );
    }
}
